import logging

from coin.strategy.accounting.pnl_balance_printer.pnl_balance_printer import FuturesPnlBalancePrinter
from coin.strategy.accounting.pnl_balance_printer.util import calculate_unrealized_pnl


class HuobiFuturesPnlBalancePrinter(FuturesPnlBalancePrinter):
  def __init__(self, products, bookmap, reserve_map, logger=None):
    super().__init__(products,
                     bookmap,
                     reserve_map,
                     logger=(logger or logging.getLogger('HuobiFuturesPnlBalancePrinter')))

  def _get_pos(self, product):
    book = self._bookmap.get_book(product)
    if book is None or not book.has_ask() or not book.has_bid():
      return None, None

    pos = self._og.get_huobi_futures_position(product)
    if pos is None:
      self._logger.warning("pos is None")
      return None, None

    if product.base.currency == 'BTC':
      pos_multiplier = 100.
    else:
      pos_multiplier = 10.

    long_pos = pos.long * pos_multiplier
    long_unrealized_pnl = calculate_unrealized_pnl(product,
                                                   long_pos,
                                                   pos.long_avg_price,
                                                   book.ask0().price,
                                                   book.bid0().price)

    short_pos = -pos.short * pos_multiplier
    short_unrealized_pnl = calculate_unrealized_pnl(product,
                                                    short_pos,
                                                    pos.short_avg_price,
                                                    book.ask0().price,
                                                    book.bid0().price)

    net_pos = long_pos + short_pos
    net_unrealized_pnl = long_unrealized_pnl + short_unrealized_pnl
    return net_pos, net_unrealized_pnl
